<template>
  <cml-module
    :moduleName="$t('cmlpanel.data')"
    icon="shujuguanli"
    v-bind="$attrs"
  >
    <cml-module-item v-if="$_auth.includes('dataSource')" :title="titleText">
      <a-select
        size="small"
        :value="type"
        :options="option"
        style="width: 120px"
        @change="dataSourceChange"
      >
      </a-select>
    </cml-module-item>
  </cml-module>
</template>
<script>
import { Select } from 'ant-design-vue'
import CmlModule from '../cml-module'
import CmlModuleItem from '../cml-module-item'
import * as anov from 'anov-core'

export default {
  name: 'DataSource',
  inheritAttrs: false,
  components: {
    ASelect: Select,
    CmlModule,
    CmlModuleItem
  },
  model: {},
  props: {},
  data() {
    return {
      value: 'DataSource',
      option: [],
      DataServerType: {
        RESTFUL: 'restful',
        WEBSOCKET: 'websocket',
        FILE: 'file',
        MOCK: 'mock',
        GRAPHQL: 'graphql'
      }
    }
  },
  computed: {
    ...anov.dataSourceServer.mapState(['type']),
    titleText() {
      return this.$t('cmlpanel.dataSource')
    }
  },
  watch: {
    type(v, v1) {
      console.log('datasourceType:'+v1+'->'+v)
      this.change(v)
    }
  },
  created() {},
  mounted() {
    this.getOptions()
  },
  beforeDestroy() {},
  methods: {
    dataSourceChange(value) {
      if (value == this.type) return
      // this.change(value)
      app.dataSourceServer.type = value
    },
    getOptions() {
      let obj = { ...this.DataServerType },
        objArr = [],
        arr = []
      objArr = Object.values(obj)
      for (let i = 0; i < objArr.length; i++) {
        arr.push({ label: objArr[i], value: objArr[i] })
      }
      
      
      this.option = this.option.concat(arr)
    },
    change(v, isInit = false) {
      // if (v == this.type) return
      anov.dataSourceServer.type = v
      if (app.api) {
        try {
          app.api.destroy && app.api.destroy()
        } catch (e) {
          app.dataSourceServer.addError('destroy datasource error,' + e.message)
        }
      }

      app.api = anov.dataSourceServer.create()

      try {
        setTimeout(() => {
          let path = app.runtimeServer.getCurrentContext().$route.path
          app.api && app.api.init && app.api.init(path)
        }, 0);
      } catch (e) {
        app.dataSourceServer.addError('datasource change init error,' + e.message)
      }

      let msg = this.$t('dataSource.changeInfo') + ':' + v
      anov.voiceFeedbackServer.speak(msg)
      anov.dataSourceServer.addInfo(msg)
      app.msg({ type: 'info', content: msg })
    }
  }
}
</script>
<style lang="scss" scoped></style>
